const utils = require("../utils");

const clients = []
const clientItem = {
  clientId: '',
  res: null,
}

exports.getServerDate = (res, clientId) => {
  res.write(send({
    clientId,
    message: '当前时间：' + utils.parseTime(new Date())
  }))
}

exports.createClient = res => {
  const clientItem = {
    clientId: utils.buildUUID(),
    res
  }

  const { clientId } = clientItem

  res.write(send({
    clientId,
    message: '连接成功！'
  }))

  clients.push(clientItem)

  console.log(`当前连接数：${clients.length}`)

  return clientId
}

exports.destroyClient = (clientId) => {
  const clientIndex = clients.findIndex(client => client.clientId === clientId)
  if (clientIndex >= 0) {
    clients.splice(clients.indexOf(clientId), 1)
  } else {
    throw new Error(`未找到该客户端 clientId：${clientId}`)
  }
  console.log(`当前连接数：${clients.length}`)
}

exports.postServerMessage = (clientId, message) => {
  const clientItem = clients.find(client => client.clientId === clientId)
  if (clientItem) {
    clientItem.res.write(send({
      clientId,
      message
    }))
    return true
  }
  return false
}


function send(message) {
  return `data: ${JSON.stringify(message)}\n\n`
}
